package org.urchr.beorganized.mobile.pages.secured.browse;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.urchr.beorganized.mobile.base.Application;
import org.urchr.beorganized.mobile.base.MobileSession;
import org.urchr.beorganized.mobile.base.components.link.MobileLink;
import org.urchr.beorganized.mobile.base.network.NetworkException;
import org.urchr.beorganized.mobile.base.network.XMLRequest;
import org.urchr.beorganized.mobile.pages.secured.agenda.AgendaPage;
import org.urchr.beorganized.mobile.pages.secured.base.SecuredPage;
import org.urchr.beorganized.mobile.pages.secured.edit.EditPage;
import org.urchr.beorganized.mobile.pages.secured.starred.StarredPage;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class BrowsePage extends SecuredPage {
	
	private String getReadableSize(int size){
		if(size<1024)
			return size+" B";
		if(size>=1024*1024)
			return (size/(1024*1024))+" MB";
		return (size/1024)+" KB";
	}
	
	public BrowsePage(PageParameters parameters) {
		super(parameters);
		final int noteID = parameters!=null?parameters.getAsInteger("id", -1):-1;
		
		if(noteID!=-1){
			add(new MobileLink("agenda", "action/tasks.png", 
					new BookmarkablePageLink("clink", AgendaPage.class, new PageParameters("id="+noteID)), "Agenda"));			
		}else{
			add(new Label("agenda"));
		}
		add(new MobileLink("starred", "action/star.png", 
				new BookmarkablePageLink("clink", StarredPage.class, new PageParameters("id="+noteID)), "Starred notes"));

		XMLRequest request = new XMLRequest("LoadTree");
		request.addParameter("noteid", ""+noteID);
		request.addParameter("loaddata", "true");
		request.addParameter("loadchildren", "false");
		resetError();
		try {
			Element root = request.callOperation();
			int parentID = safeInt(root.getAttribute("parentid"), -1);
			add(new MobileLink("note_title", "types/p"+root.getAttribute("customIcon")+".png", 
					new BookmarkablePageLink("clink", BrowsePage.class, new PageParameters("id="+noteID)), 
					root.getAttribute("text")));
			if(parentID!=-1){
				add(new MobileLink("top", "action/top.png", 
						new BookmarkablePageLink("clink", BrowsePage.class, 
								new PageParameters("id="+parentID)), "Level up"));
			}else{
				if(noteID==-1){
					add(new Label("top"));
					addOrReplace(new Label("note_title"));
				}else{
					add(new MobileLink("top", "action/top.png", 
							new BookmarkablePageLink("clink", BrowsePage.class), "Go to top"));					
				}
			}
			List<Element> children = new ArrayList<Element>();
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				if(nl.item(i) instanceof Element){
					children.add((Element) nl.item(i));
				}
			}
			
			add(new ListView<Element>("children", children){

				private static final long serialVersionUID = -3025828713339293379L;

				@Override
				protected void populateItem(ListItem<Element> item) {
					item.add(new MobileLink("note", 
							"types/p"+item.getModelObject().getAttribute("icon")+".png", 
							item.getModelObject().getAttribute("add_icon"),
							new BookmarkablePageLink("clink", BrowsePage.class, 
									new PageParameters("id="+item.getModelObject().getAttribute("id"))), 
									item.getModelObject().getAttribute("text")));
				}
				
			});
			
			int noteType = safeInt(root.getAttribute("type"), 0);
			String content = "";
			boolean hideContent = false;
			switch (noteType) {
				case 0:
					content = escapeHTML(root.getAttribute("textContent"));
					if("".equals(content))
						hideContent = true;
					else
						content = "<code>"+escapeHTML(root.getAttribute("textContent"))+"</code>";
					break;
				case 1:
					content = "File: "+root.getAttribute("fileName")+", size: "+
						getReadableSize(safeInt(root.getAttribute("fileSize"), 0))+
						"<br/><a href=\""+MobileSession.getSession().getServer()+
						"file.Download?sharecode="+root.getAttribute("shareCode")+"\"><img src=\""+MobileSession.getSession().getServer()+
						"file.Download?sharecode="+root.getAttribute("shareCode")+"&width=200\"/></a>";
					break;
				case 3:
					content = "<img src=\""+Application.IMG_PREFIX+"priority/p"+root.getAttribute("priority")+".png\">";
					content += ("true".equals(root.getAttribute("completed"))?"Completed":"Incomplete")+"<br/>";
					if(null!=root.getAttribute("datesInfo") && !"".equals(root.getAttribute("datesInfo")))
						content +="Due date:<span class=\"urgent"+root.getAttribute("urgentLevel")+"\">"+root.getAttribute("datesInfo")+"</span><br/>";
					content += "<code>"+escapeHTML(root.getAttribute("textContent"))+"</code>";
					break;
				case 4:
					content = "<span class=\"urgent"+root.getAttribute("urgentLevel")+"\">"+root.getAttribute("datesInfo")+"</span><br/><code>"+escapeHTML(root.getAttribute("textContent"))+"</code>";
					break;
				case 5:
					content = "<a target=\"_blank\" href=\""+root.getAttribute("url")+"\">"+root.getAttribute("url")+"</a><br/><code>"+escapeHTML(root.getAttribute("textContent"))+"</code>";
					break;
				case 6:
					content = "File: "+root.getAttribute("fileName")+", size: "+
						getReadableSize(safeInt(root.getAttribute("fileSize"), 0))+
						"<br/><a href=\""+MobileSession.getSession().getServer()+
						"file.Download?sharecode="+root.getAttribute("shareCode")+"\">Download file</a>";
					break;
			}
			if(hideContent)
				add(new Label("content").setVisible(false));
			else
				add(new Label("content", content).setEscapeModelStrings(false));
			boolean canCreate = "true".equals(root.getAttribute("canCreate"));
			boolean canEdit = "true".equals(root.getAttribute("canEdit")) && noteType!=1 && noteType!=6;
			boolean canDelete = "true".equals(root.getAttribute("canDelete")) && 
						safeInt(root.getAttribute("level"), 0)>0;
			if(canEdit)
				add(new MobileLink("edit", "action/edit.png", 
						new BookmarkablePageLink("clink", 
								EditPage.class, new PageParameters("id="+noteID)), "Edit"));
			else
				add(new Label("edit"));
			if(canCreate){
				add(new MobileLink("new_text", "types/p0.png", 
						new BookmarkablePageLink("clink", 
								EditPage.class, new PageParameters("id="+noteID+",new=true,type=0")), "New text note"));
				add(new MobileLink("new_task", "types/p3.png", 
						new BookmarkablePageLink("clink", 
								EditPage.class, new PageParameters("id="+noteID+",new=true,type=3")), "New task"));
				add(new MobileLink("new_event", "types/p4.png", 
						new BookmarkablePageLink("clink", 
								EditPage.class, new PageParameters("id="+noteID+",new=true,type=4")), "New event"));
				add(new MobileLink("new_bmark", "types/p5.png", 
						new BookmarkablePageLink("clink", 
								EditPage.class, new PageParameters("id="+noteID+",new=true,type=5")), "New bookmark"));				
			}else{
				add(new Label("new_text"));
				add(new Label("new_task"));
				add(new Label("new_event"));
				add(new Label("new_bmark"));
			}
			if(canDelete){
				add(new MobileLink("archive", "action/remove.png", 
						new Link("clink"){
							private static final long serialVersionUID = 5225602929933217316L;
							@Override
							public void onClick() {
								resetError();
								XMLRequest request = new XMLRequest("RemoveNote");
								request.addParameter("noteid", noteID);
								try {
									Element e = request.callOperation();
									setResponsePage(BrowsePage.class, 
											new PageParameters("id="+e.getAttribute("parentid")));
								} catch (NetworkException e) {
									e.printStackTrace();
									showError(e.getErrorString());
								}
							}
					
				}, "Archive"));
			}else{
				add(new Label("archive"));
			}
			add(new Label("enc_flag").setVisible(canCreate || canEdit || canDelete));
		} catch (NetworkException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			add(new MobileLink("top", "action/top.png", 
					new BookmarkablePageLink("clink", BrowsePage.class), "Go to top"));
			add(new Label("note_title"));
			add(new Label("children"));
			add(new Label("enc_flag").setVisible(false));
			showError(e.getErrorString());
		}
	}
	
}
